import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect, useRef } from "react";
import { formatChildTree } from "../RowMerge/tools";
import { getDsToZlData } from "../../api/DesignTableApi";
//import {filterCpasTable } from './tools';
import { ColumnHeightOutlined, SortAscendingOutlined, SortDescendingOutlined,
// CheckOutlined,
 } from "@ant-design/icons";
import { Checkbox, Card, Modal, message, TreeSelect, Col, Row, Form, Radio, } from "antd";
import { Button } from "devextreme-react/button";
import "./_style.less";
import Draggable from "react-draggable";
const SortModalComponent = (props) => {
    const { isOpen, handleOpen, _this } = props;
    const [sortForm] = Form.useForm();
    const { setFieldsValue } = sortForm;
    const [selectColumnNum, setSelectColumnNum] = useState(null);
    const [columnData, setColumnData] = useState([]);
    const [disabled, setDisabled] = useState(true);
    const [bounds, setBounds] = useState({
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
    });
    const draggleRef = useRef(null);
    //获取列数据
    const getColumnData = () => {
        const { header } = _this.gridRef.dsSourceData;
        const headerData = header.slice(1, header.length - 1);
        let selcetOptions = [];
        for (let i = 0; i < headerData.length; i++) {
            const currentHead = headerData[i];
            let prevHeadChildLen = 0;
            if (i > 0) {
                const prevHead = headerData[i - 1];
                if (prevHead?.children && prevHead?.children.length) {
                    prevHeadChildLen =
                        prevHead?.children && prevHead?.children.length
                            ? prevHead?.children.length - 1
                            : 0;
                }
            }
            const columnNum = i + 1 + prevHeadChildLen;
            headerData[i].columnNum = columnNum;
            const children = formatChildTree(currentHead.children, i + 1 + prevHeadChildLen, "all");
            if (((!children || !children.length) && !currentHead?.config?.isRuntime) ||
                children.length) {
                selcetOptions.push({
                    key: currentHead.columnNum,
                    label: currentHead.label,
                    columnNum,
                    value: `${currentHead.label}${currentHead.columnNum}${i}`,
                    children,
                });
            }
        }
        setColumnData([...selcetOptions]);
        return selcetOptions;
    };
    const loadSortFetchApi = async () => {
        const columnData = await getColumnData();
        const { tableConfig = {} } = _this.gridRef.getCpasTableGrid();
        let { sortCfg = {} } = tableConfig;
        const currentColumnNum = sortCfg?.columnNum
            ? sortCfg?.columnNum
            : selectColumnNum;
        if (currentColumnNum && columnData && columnData.length) {
            const currentColumn = columnData.filter((item) => item.columnNum === currentColumnNum);
            if (currentColumn && currentColumn.length) {
                setSelectColumnNum(currentColumn.columnNum);
            }
        }
        else if (!currentColumnNum && columnData && columnData.length) {
            const currentData = columnData[0];
            setSelectColumnNum(currentData.columnNum);
        }
        /*sortCfg = {
          column_val: "金额21",
          selectColumnNum: 2,
          is_blank_row: true
        };*/
        if (sortCfg && Object.keys(sortCfg).length > 0) {
            setFieldsValue(sortCfg);
            setSelectColumnNum(sortCfg.selectColumnNum);
        }
        else {
            const columnNum = columnData && columnData.length ? columnData[0].columnNum : "";
            setFieldsValue({
                column_val: columnData && columnData.length ? columnData[0].value : "",
                sort: "",
                other_sort: false,
                selectColumnNum: columnNum,
            });
            setSelectColumnNum(columnNum);
        }
    };
    useEffect(() => {
        loadSortFetchApi();
    }, [isOpen]);
    const onSelectChange = (value, label, extra) => {
        const columnNum = extra.triggerNode.props.columnNum
            ? extra.triggerNode.props.columnNum
            : 0;
        setSelectColumnNum(columnNum);
    };
    const onClearTable = async () => {
        console.log("clear table");
        setFieldsValue({
            column_val: columnData && columnData.length ? columnData[0].value : "",
            sort: "",
            other_sort: false,
            selectColumnNum: columnData && columnData.length ? columnData[0].columnNum : "",
        });
        delete _this.gridRef.tableConfig["sortCfg"];
        const dsSourceData = _this.gridRef.dsSourceData;
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const tableConfig = _this.gridRef.tableConfig;
        try {
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, {
                ...tableConfig,
            }, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastable实例
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
                handleOpen(false);
                message.success("排序条件清空成功");
                _this.gridRef.setTableContentChange(true, {
                    type: "排序清空",
                    params: {},
                });
            }
        }
        catch (e) {
            message.error("操作失败，请检查配置项重试");
            throw e;
        }
    };
    const onCancel = () => {
        console.log("onCancel");
        if (columnData && columnData.length) {
            setSelectColumnNum(columnData[0].columnNum);
        }
        else {
            setSelectColumnNum(null);
        }
        handleOpen(false);
    };
    const onFinishSave = async () => {
        let formValues = sortForm.getFieldsValue(); // 获取表单数据
        if (selectColumnNum) {
            formValues["selectColumnNum"] = selectColumnNum;
        }
        console.log("表单数据:", formValues);
        const dsSourceData = _this.gridRef.dsSourceData;
        console.log(dsSourceData, "dsSourceData111");
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const { tableConfig } = _this.gridRef.getCpasTableGrid();
        let newTableCfg = {
            ...tableConfig,
        };
        newTableCfg["sortCfg"] = {
            other_sort: formValues?.other_sort,
        };
        // if (formValues?.other_sort) {
        //   newTableCfg["sortCfg"] = {
        //     other_sort: formValues?.other_sort,
        //   };
        // }
        if (formValues.sort) {
            newTableCfg = {
                ...newTableCfg,
                sortCfg: {
                    ...formValues,
                },
            };
        }
        console.log(newTableCfg, "newTableCfg");
        try {
            /**本地调试专用 */
            /*let zlTableData: any = {};
            const data = sortCpasTable(
              dsSourceData,
              newTableCfg,
            );
            zlTableData.data = data;*/
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, newTableCfg, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastable实例
                console.log(refs, "refs1111");
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
                handleOpen(false);
                message.success("排序条件设置成功");
                _this.gridRef.setTableContentChange(true, {
                    type: "排序保存",
                    params: {
                        ...newTableCfg.sortCfg,
                    },
                });
            }
        }
        catch (e) {
            message.error("操作失败，请检查配置项重试");
            throw e;
        }
    };
    const tableSettingLeft = () => {
        return (_jsxs(React.Fragment, { children: [_jsx(ColumnHeightOutlined, { style: { color: "green" } }), " \u6392\u5E8F"] }));
    };
    const tableSettingRight = () => {
        return (_jsxs(React.Fragment, { children: [_jsx(Button, { onClick: () => onClearTable(), type: "default", children: "\u6392\u5E8F\u6E05\u7A7A" }), _jsx(Button, { onClick: onFinishSave, type: "default", children: "\u786E\u5B9A" })] }));
    };
    const onStart = (_event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    return (_jsx(React.Fragment, { children: _jsx(Modal, { open: isOpen, width: "90%", onCancel: onCancel, footer: null, className: "setting zl-modal", keyboard: false, maskClosable: false, destroyOnClose: true, forceRender: true, title: _jsx(Card, { title: tableSettingLeft(), extra: tableSettingRight(), bordered: false, className: "merge-card-title", style: {
                    cursor: "move",
                }, onMouseOver: () => {
                    if (disabled) {
                        setDisabled(false);
                    }
                }, onMouseOut: () => {
                    setDisabled(true);
                }, 
                // fix eslintjsx-a11y/mouse-events-have-key-events
                // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
                onFocus: () => { }, onBlur: () => { } }), modalRender: (modal) => (_jsx(Draggable, { disabled: disabled, bounds: bounds, nodeRef: draggleRef, onStart: (event, uiData) => onStart(event, uiData), children: _jsx("div", { ref: draggleRef, children: modal }) })), children: _jsx("div", { className: "filter-card-content", children: _jsx("div", { className: "filter-condition sort-condition", children: _jsx(Form, { form: sortForm, name: "filter_form", layout: "inline", onFinish: onFinishSave, initialValues: {
                            column_val: columnData && columnData.length ? columnData[0].value : "",
                        }, children: _jsxs(Row, { children: [_jsxs(Col, { span: 18, children: [_jsx(Form.Item, { name: "column_val", label: "\u8BF7\u9009\u62E9\u5217\uFF1A", children: _jsx(TreeSelect, { onChange: onSelectChange, dropdownMatchSelectWidth: false, treeData: columnData, treeDefaultExpandAll: true, style: { width: 150 } }) }), _jsx(Form.Item, { name: "sort", children: _jsxs(Radio.Group, { children: [_jsxs(Radio, { value: "ascend", children: [_jsx(SortAscendingOutlined, {}), "\u5347\u5E8F"] }), _jsxs(Radio, { value: "descend", children: [_jsx(SortDescendingOutlined, {}), "\u964D\u5E8F"] })] }) })] }), _jsx(Col, { span: 6, children: _jsx(Form.Item, { name: "other_sort", valuePropName: "checked", children: _jsx(Checkbox, { children: "\u5C06\u201D\u5176\u4ED6\u201C\u6392\u6700\u540E" }) }) })] }) }) }) }) }) }));
};
export default SortModalComponent;
